import javax.swing.*;
import javax.swing.border.*;
import javax.swing.table.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.util.*;
import java.util.List;


public class LibraryGUI extends JFrame {
    private Library library;
    private JTabbedPane tabbedPane;


    // 颜色主题
    private static final Color PRIMARY_COLOR = new Color(41, 128, 185);
    private static final Color SECONDARY_COLOR = new Color(52, 152, 219);
    private static final Color ACCENT_COLOR = new Color(231, 76, 60);
    private static final Color BACKGROUND_COLOR = new Color(255, 250, 250);
    private static final Color TABLE_HEADER_COLOR = new Color(52, 73, 94);


    public Library getLibrary() {
        return library;
    }

    public void setLibrary(Library library) {
        this.library = library;
    }

    public void refreshStatistics() {
        // 刷新统计面板数据
        if (tabbedPane.getTabCount() > 4) {
            JPanel statsPanel = (JPanel) tabbedPane.getComponentAt(4);
            statsPanel.removeAll();
            statsPanel.add(createStatisticsPanel());
            statsPanel.revalidate();
            statsPanel.repaint();
        }
    }
    public LibraryGUI() {
        super("图书馆管理系统");
        library = new Library();


        // 设置应用图标
        setIconImage(getDefaultLibraryIcon());


        // 添加示例数据
        initializeSampleData();


        // 设置窗口属性
        setSize(900, 650);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);


        // 创建主面板
        JPanel mainPanel = new JPanel(new BorderLayout());
        mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        mainPanel.setBackground(BACKGROUND_COLOR);


        // 创建标题面板
        JPanel titlePanel = createTitlePanel();
        mainPanel.add(titlePanel, BorderLayout.NORTH);


        // 创建选项卡面板
        tabbedPane = new JTabbedPane();
        tabbedPane.setBackground(PRIMARY_COLOR);
        tabbedPane.setForeground(Color.BLACK);
        tabbedPane.setFont(new Font("微软雅黑", Font.BOLD, 14));


        // 添加各个功能面板
        tabbedPane.addTab("📚 图书管理", createBookManagementPanel());
        tabbedPane.addTab("👥 用户管理", createUserManagementPanel());
        tabbedPane.addTab("🔄 借阅管理", createLoanManagementPanel());
        tabbedPane.addTab("🔍 搜索图书", createSearchPanel());
        tabbedPane.addTab("📊 借阅统计", createStatisticsPanel());


        mainPanel.add(tabbedPane, BorderLayout.CENTER);


        // 创建底部状态栏
        JPanel statusPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        statusPanel.setBorder(BorderFactory.createMatteBorder(1, 0, 0, 0, Color.GRAY));
        statusPanel.setBackground(new Color(158, 195, 198));


        JLabel statusLabel = new JLabel("就绪 | 图书总数: " + library.getAllBooks().size() +
                " | 用户总数: " + library.getAllUsers().size());
        statusLabel.setFont(new Font("微软雅黑", Font.PLAIN, 12));
        statusPanel.add(statusLabel);


        mainPanel.add(statusPanel, BorderLayout.SOUTH);


        add(mainPanel);
        setVisible(true);
    }

    private Image getDefaultLibraryIcon() {
        int size = 64; // 图标大小
        BufferedImage image = new BufferedImage(size, size, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = image.createGraphics();
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        // 绘制背景
        GradientPaint gradient = new GradientPaint(0, 0, new Color(52, 152, 219), size, size, new Color(41, 128, 185));
        g2d.setPaint(gradient);
        g2d.fillRoundRect(0, 0, size, size, 20, 20);

        // 绘制书本
        g2d.setColor(Color.WHITE);
        int bookWidth = size / 2;
        int bookHeight = size * 3 / 4;
        int bookX = (size - bookWidth) / 2;
        int bookY = (size - bookHeight) / 2;

        // 书本主体
        g2d.fillRoundRect(bookX, bookY, bookWidth, bookHeight, 10, 10);

        // 书脊
        g2d.setColor(new Color(31, 97, 141));
        g2d.fillRoundRect(bookX, bookY, bookWidth / 6, bookHeight, 5, 5);

        // 书页线
        g2d.setColor(new Color(220, 220, 220, 200));
        for (int i = 1; i < 5; i++) {
            int lineY = bookY + (bookHeight * i) / 5;
            g2d.drawLine(bookX + bookWidth / 4, lineY, bookX + bookWidth - 5, lineY);
        }

        // 装饰图标
        g2d.setColor(new Color(241, 196, 15)); // 黄色
        int starSize = size / 6;
        g2d.fillPolygon(new int[] {size - starSize, size - starSize/2, size},
                new int[] {starSize, 0, starSize}, 3);

        g2d.dispose();
        return image;
    }
    private ImageIcon createImageIcon(String path) {
        java.net.URL imgURL = getClass().getResource(path);
        if (imgURL != null) {
            return new ImageIcon(imgURL);
        } else {
            System.err.println("找不到文件: " + path);
            return new ImageIcon();
        }
    }


    private JPanel createTitlePanel() {
        JPanel panel = new JPanel();
        panel.setBackground(PRIMARY_COLOR);
        panel.setBorder(BorderFactory.createEmptyBorder(10, 20, 10, 20));


        JLabel titleLabel = new JLabel("图书馆管理系统");
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 28));
        titleLabel.setForeground(Color.BLACK);


        JLabel subtitleLabel = new JLabel("图书借阅、管理一站式解决方案");
        subtitleLabel.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        subtitleLabel.setForeground(new Color(255, 252, 252));


        panel.setLayout(new BorderLayout());
        panel.add(titleLabel, BorderLayout.WEST);
        panel.add(subtitleLabel, BorderLayout.EAST);


        return panel;
    }


    private void initializeSampleData() {
        // 添加示例图书
        library.addBook(new Book("978-7-02-000001", "红楼梦", "曹雪芹", "小说"));
        library.addBook(new Book("978-7-03-000002", "Java编程思想", "Bruce Eckel", "科技"));
        library.addBook(new Book("978-7-04-000003", "世界简史", "赫伯特·乔治·威尔斯", "历史"));
        library.addBook(new Book("978-7-05-000004", "艺术的故事", "贡布里希", "艺术"));
        library.addBook(new Book("978-7-06-000005", "教育学原理", "王道俊", "教育"));
        library.addBook(new Book("978-7-07-000006", "人类简史", "尤瓦尔·赫拉利", "历史"));
        library.addBook(new Book("978-7-08-000007", "三体", "刘慈欣", "小说"));
        library.addBook(new Book("978-7-09-000008", "时间简史", "霍金", "科技"));


        // 添加示例用户
        library.addUser(new User("U001", "张三", "13800138000"));
        library.addUser(new User("U002", "李四", "13900139000"));
        library.addUser(new User("U003", "王五", "13700137000"));
        library.addUser(new User("U004", "赵六", "13600136000"));


        // 模拟借阅记录
        library.borrowBook("U001", "978-7-02-000001");
        library.borrowBook("U002", "978-7-03-000002");
        library.borrowBook("U003", "978-7-04-000003");
    }


    // 图书管理面板
    private JPanel createBookManagementPanel() {
        JPanel panel = new JPanel(new BorderLayout(10, 10));
        panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        panel.setBackground(BACKGROUND_COLOR);


        // 创建表格模型
        String[] columnNames = {"ISBN", "书名", "作者", "分类", "状态", "借阅者"};
        DefaultTableModel model = new DefaultTableModel(columnNames, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false; // 使表格不可编辑
            }
        };


        // 填充表格数据
        for (Book book : library.getAllBooks()) {
            String borrowerName = "";
            if (!book.isAvailable()) {
                borrowerName = library.getBorrowerName(book.getIsbn());
            }


            Object[] rowData = {
                    book.getIsbn(),
                    book.getTitle(),
                    book.getAuthor(),
                    book.getCategory(),
                    book.isAvailable() ? "可借" : "已借",
                    borrowerName
            };
            model.addRow(rowData);
        }


        JTable table = new JTable(model);
        customizeTable(table);


        JScrollPane scrollPane = new JScrollPane(table);
        scrollPane.setBorder(BorderFactory.createEmptyBorder());
        panel.add(scrollPane, BorderLayout.CENTER);


        // 底部按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 15, 10));
        buttonPanel.setBackground(BACKGROUND_COLOR);


        JButton addButton = createStyledButton("添加图书", PRIMARY_COLOR);
        addButton.addActionListener(e -> showAddBookDialog());


        JButton removeButton = createStyledButton("删除图书", ACCENT_COLOR);
        removeButton.addActionListener(e -> {
            int selectedRow = table.getSelectedRow();
            if (selectedRow >= 0) {
                String isbn = (String) table.getValueAt(selectedRow, 0);
                library.removeBook(isbn);
                model.removeRow(selectedRow);
                showMessage("图书删除成功！", "操作成功", JOptionPane.INFORMATION_MESSAGE);
            } else {
                showMessage("请选择要删除的图书！", "警告", JOptionPane.WARNING_MESSAGE);
            }
        });


        JButton refreshButton = createStyledButton("刷新列表", SECONDARY_COLOR);
        refreshButton.addActionListener(e -> refreshBookTable());


        buttonPanel.add(addButton);
        buttonPanel.add(removeButton);
        buttonPanel.add(refreshButton);


        panel.add(buttonPanel, BorderLayout.SOUTH);


        return panel;
    }


    private void customizeTable(JTable table) {
        table.setRowHeight(30);
        table.setFont(new Font("微软雅黑", Font.PLAIN, 14));


        // 设置表头样式
        JTableHeader header = table.getTableHeader();
        header.setFont(new Font("微软雅黑", Font.BOLD, 14));
        header.setBackground(TABLE_HEADER_COLOR);
        header.setForeground(Color.BLACK);
        header.setReorderingAllowed(false);


        // 设置表格渲染器
        table.setDefaultRenderer(Object.class, new DefaultTableCellRenderer() {
            @Override
            public Component getTableCellRendererComponent(JTable table, Object value,
                                                           boolean isSelected, boolean hasFocus, int row, int column) {
                Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);


                // 设置交替行颜色
                if (row % 2 == 0) {
                    c.setBackground(Color.WHITE);
                } else {
                    c.setBackground(new Color(240, 248, 255));
                }


                // 设置状态列颜色
                if (column == 4) {
                    String status = (String) value;
                    if ("已借".equals(status)) {
                        c.setForeground(new Color(192, 57, 43));
                        setFont(getFont().deriveFont(Font.BOLD));
                    } else {
                        c.setForeground(new Color(39, 174, 96));
                        setFont(getFont().deriveFont(Font.BOLD));
                    }
                } else {
                    c.setForeground(Color.BLACK);
                }


                // 设置选择行样式
                if (isSelected) {
                    c.setBackground(new Color(189, 224, 254));
                }


                setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 10));
                setHorizontalAlignment(SwingConstants.LEFT);
                return c;
            }
        });
    }


    private JButton createStyledButton(String text, Color bgColor) {
        JButton button = new JButton(text);
        button.setFont(new Font("微软雅黑", Font.BOLD, 14));
        button.setBackground(bgColor);
        button.setForeground(Color.BLACK);
        button.setFocusPainted(false);
        button.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(bgColor.darker(), 1),
                BorderFactory.createEmptyBorder(8, 20, 8, 20)
        ));


        // 添加鼠标悬停效果
        button.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseEntered(MouseEvent e) {
                button.setBackground(bgColor.brighter());
            }


            @Override
            public void mouseExited(MouseEvent e) {
                button.setBackground(bgColor);
            }
        });


        return button;
    }


    private void showAddBookDialog() {
        JDialog dialog = new JDialog(this, "添加新图书", true);
        dialog.setSize(500, 350);
        dialog.setLayout(new BorderLayout());
        dialog.setLocationRelativeTo(this);


        JPanel contentPanel = new JPanel(new GridLayout(5, 2, 15, 15));
        contentPanel.setBorder(BorderFactory.createEmptyBorder(20, 30, 20, 30));


        JLabel isbnLabel = new JLabel("ISBN:");
        isbnLabel.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        JTextField isbnField = new JTextField();
        isbnField.setFont(new Font("微软雅黑", Font.PLAIN, 14));


        JLabel titleLabel = new JLabel("书名:");
        titleLabel.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        JTextField titleField = new JTextField();
        titleField.setFont(new Font("微软雅黑", Font.PLAIN, 14));


        JLabel authorLabel = new JLabel("作者:");
        authorLabel.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        JTextField authorField = new JTextField();
        authorField.setFont(new Font("微软雅黑", Font.PLAIN, 14));


        JLabel categoryLabel = new JLabel("分类:");
        categoryLabel.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        JComboBox<String> categoryCombo = new JComboBox<>();
        for (String category : library.getCategories()) {
            categoryCombo.addItem(category);
        }
        categoryCombo.setFont(new Font("微软雅黑", Font.PLAIN, 14));


        contentPanel.add(isbnLabel);
        contentPanel.add(isbnField);
        contentPanel.add(titleLabel);
        contentPanel.add(titleField);
        contentPanel.add(authorLabel);
        contentPanel.add(authorField);
        contentPanel.add(categoryLabel);
        contentPanel.add(categoryCombo);


        // 按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 10));
        buttonPanel.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 0));


        JButton saveButton = createStyledButton("保存", PRIMARY_COLOR);
        saveButton.addActionListener(e -> {
            String isbn = isbnField.getText().trim();
            String title = titleField.getText().trim();
            String author = authorField.getText().trim();
            String category = (String) categoryCombo.getSelectedItem();


            if (isbn.isEmpty() || title.isEmpty() || author.isEmpty()) {
                showMessage("请填写所有字段！", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }


            if (library.findBook(isbn) != null) {
                showMessage("该ISBN已存在！", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }


            Book newBook = new Book(isbn, title, author, category);
            library.addBook(newBook);
            dialog.dispose();
            refreshBookTable();
            showMessage("图书添加成功！", "操作成功", JOptionPane.INFORMATION_MESSAGE);
        });


        JButton cancelButton = createStyledButton("取消", new Color(137, 174, 177));
        cancelButton.addActionListener(e -> dialog.dispose());


        buttonPanel.add(saveButton);
        buttonPanel.add(cancelButton);


        dialog.add(contentPanel, BorderLayout.CENTER);
        dialog.add(buttonPanel, BorderLayout.SOUTH);


        dialog.setVisible(true);
    }


    private void refreshBookTable() {
        JPanel bookPanel = (JPanel) tabbedPane.getComponentAt(0);
        JScrollPane scrollPane = (JScrollPane) bookPanel.getComponent(0);
        JTable table = (JTable) scrollPane.getViewport().getView();
        DefaultTableModel model = (DefaultTableModel) table.getModel();


        model.setRowCount(0);
        for (Book book : library.getAllBooks()) {
            String borrowerName = "";
            if (!book.isAvailable()) {
                borrowerName = library.getBorrowerName(book.getIsbn());
            }


            Object[] rowData = {
                    book.getIsbn(),
                    book.getTitle(),
                    book.getAuthor(),
                    book.getCategory(),
                    book.isAvailable() ? "可借" : "已借",
                    borrowerName
            };
            model.addRow(rowData);
        }
    }


    // 用户管理面板
    private JPanel createUserManagementPanel() {
        JPanel panel = new JPanel(new BorderLayout(10, 10));
        panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        panel.setBackground(BACKGROUND_COLOR);


        // 创建表格模型
        String[] columnNames = {"用户ID", "姓名", "电话", "借阅数量"};
        DefaultTableModel model = new DefaultTableModel(columnNames, 0);


        // 填充表格数据
        for (User user : library.getAllUsers()) {
            Object[] rowData = {
                    user.getUserId(),
                    user.getName(),
                    user.getPhone(),
                    user.getBorrowedBooks().size()
            };
            model.addRow(rowData);
        }


        JTable table = new JTable(model);
        customizeTable(table);


        JScrollPane scrollPane = new JScrollPane(table);
        scrollPane.setBorder(BorderFactory.createEmptyBorder());
        panel.add(scrollPane, BorderLayout.CENTER);


        // 底部按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 15, 10));
        buttonPanel.setBackground(BACKGROUND_COLOR);


        JButton addButton = createStyledButton("添加用户", PRIMARY_COLOR);
        addButton.addActionListener(e -> showAddUserDialog());


        JButton removeButton = createStyledButton("删除用户", ACCENT_COLOR);
        removeButton.addActionListener(e -> {
            int selectedRow = table.getSelectedRow();
            if (selectedRow >= 0) {
                String userId = (String) table.getValueAt(selectedRow, 0);
                library.removeUser(userId);
                model.removeRow(selectedRow);
                showMessage("用户删除成功！", "操作成功", JOptionPane.INFORMATION_MESSAGE);
            } else {
                showMessage("请选择要删除的用户！", "警告", JOptionPane.WARNING_MESSAGE);
            }
        });


        JButton refreshButton = createStyledButton("刷新列表", SECONDARY_COLOR);
        refreshButton.addActionListener(e -> refreshUserTable());


        buttonPanel.add(addButton);
        buttonPanel.add(removeButton);
        buttonPanel.add(refreshButton);


        panel.add(buttonPanel, BorderLayout.SOUTH);


        return panel;
    }


    private void showAddUserDialog() {
        JDialog dialog = new JDialog(this, "添加新用户", true);
        dialog.setSize(500, 300);
        dialog.setLayout(new BorderLayout());
        dialog.setLocationRelativeTo(this);


        JPanel contentPanel = new JPanel(new GridLayout(3, 2, 15, 15));
        contentPanel.setBorder(BorderFactory.createEmptyBorder(20, 30, 20, 30));


        JLabel userIdLabel = new JLabel("用户ID:");
        userIdLabel.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        JTextField userIdField = new JTextField();
        userIdField.setFont(new Font("微软雅黑", Font.PLAIN, 14));


        JLabel nameLabel = new JLabel("姓名:");
        nameLabel.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        JTextField nameField = new JTextField();
        nameField.setFont(new Font("微软雅黑", Font.PLAIN, 14));


        JLabel phoneLabel = new JLabel("电话:");
        phoneLabel.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        JTextField phoneField = new JTextField();
        phoneField.setFont(new Font("微软雅黑", Font.PLAIN, 14));


        contentPanel.add(userIdLabel);
        contentPanel.add(userIdField);
        contentPanel.add(nameLabel);
        contentPanel.add(nameField);
        contentPanel.add(phoneLabel);
        contentPanel.add(phoneField);


        // 按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 10));
        buttonPanel.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 0));


        JButton saveButton = createStyledButton("保存", PRIMARY_COLOR);
        saveButton.addActionListener(e -> {
            String userId = userIdField.getText().trim();
            String name = nameField.getText().trim();
            String phone = phoneField.getText().trim();


            if (userId.isEmpty() || name.isEmpty() || phone.isEmpty()) {
                showMessage("请填写所有字段！", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }


            if (library.findUser(userId) != null) {
                showMessage("该用户ID已存在！", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }


            User newUser = new User(userId, name, phone);
            library.addUser(newUser);
            dialog.dispose();
            refreshUserTable();
            showMessage("用户添加成功！", "操作成功", JOptionPane.INFORMATION_MESSAGE);
        });


        JButton cancelButton = createStyledButton("取消", new Color(158, 195, 198));
        cancelButton.addActionListener(e -> dialog.dispose());


        buttonPanel.add(saveButton);
        buttonPanel.add(cancelButton);


        dialog.add(contentPanel, BorderLayout.CENTER);
        dialog.add(buttonPanel, BorderLayout.SOUTH);


        dialog.setVisible(true);
    }


    private void refreshUserTable() {
        JPanel userPanel = (JPanel) tabbedPane.getComponentAt(1);
        JScrollPane scrollPane = (JScrollPane) userPanel.getComponent(0);
        JTable table = (JTable) scrollPane.getViewport().getView();
        DefaultTableModel model = (DefaultTableModel) table.getModel();


        model.setRowCount(0);
        for (User user : library.getAllUsers()) {
            Object[] rowData = {
                    user.getUserId(),
                    user.getName(),
                    user.getPhone(),
                    user.getBorrowedBooks().size()
            };
            model.addRow(rowData);
        }
    }


    // 借阅管理面板
    private JPanel createLoanManagementPanel() {
        JPanel panel = new JPanel(new BorderLayout(10, 10));
        panel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
        panel.setBackground(new Color(230,240,255));


        // 主面板使用网格布局
        JPanel mainPanel = new JPanel(new GridLayout(2, 1, 20, 20));
        mainPanel.setBackground(new Color(230,240,255));


        // 创建借书面板
        JPanel borrowPanel = createSectionPanel("借阅图书", PRIMARY_COLOR);
        borrowPanel.setLayout(new GridLayout(3, 2, 15, 15));


        JLabel userIdLabel = createFormLabel("用户ID:");
        JTextField userIdField = createFormTextField();


        JLabel isbnLabel = createFormLabel("图书ISBN:");
        JTextField isbnField = createFormTextField();


        JButton borrowButton = createStyledButton("借阅", PRIMARY_COLOR);
        borrowButton.addActionListener(e -> {
            String userId = userIdField.getText().trim();
            String isbn = isbnField.getText().trim();


            if (userId.isEmpty() || isbn.isEmpty()) {
                showMessage("请填写用户ID和图书ISBN！", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }


            if (library.borrowBook(userId, isbn)) {
                showMessage("借阅成功！", "操作成功", JOptionPane.INFORMATION_MESSAGE);
                refreshBookTable();
                userIdField.setText("");
                isbnField.setText("");
            } else {
                showMessage("借阅失败！请检查用户ID、图书ISBN或图书是否可借。", "错误", JOptionPane.ERROR_MESSAGE);
            }
        });


        borrowPanel.add(userIdLabel);
        borrowPanel.add(userIdField);
        borrowPanel.add(isbnLabel);
        borrowPanel.add(isbnField);
        borrowPanel.add(new JLabel()); // 占位符
        borrowPanel.add(borrowButton);


        // 创建还书面板
        JPanel returnPanel = createSectionPanel("归还图书", ACCENT_COLOR);
        returnPanel.setLayout(new GridLayout(3, 2, 15, 15));


        JLabel returnUserIdLabel = createFormLabel("用户ID:");
        JTextField returnUserIdField = createFormTextField();


        JLabel returnIsbnLabel = createFormLabel("图书ISBN:");
        JTextField returnIsbnField = createFormTextField();


        JButton returnButton = createStyledButton("归还", ACCENT_COLOR);
        returnButton.addActionListener(e -> {
            String userId = returnUserIdField.getText().trim();
            String isbn = returnIsbnField.getText().trim();


            if (userId.isEmpty() || isbn.isEmpty()) {
                showMessage("请填写用户ID和图书ISBN！", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }


            if (library.returnBook(userId, isbn)) {
                showMessage("归还成功！", "操作成功", JOptionPane.INFORMATION_MESSAGE);
                refreshBookTable();
                returnUserIdField.setText("");
                returnIsbnField.setText("");
            } else {
                showMessage("归还失败！请检查用户ID、图书ISBN或图书是否已借出。", "错误", JOptionPane.ERROR_MESSAGE);
            }
        });


        returnPanel.add(returnUserIdLabel);
        returnPanel.add(returnUserIdField);
        returnPanel.add(returnIsbnLabel);
        returnPanel.add(returnIsbnField);
        returnPanel.add(new JLabel()); // 占位符
        returnPanel.add(returnButton);


        mainPanel.add(borrowPanel);
        mainPanel.add(returnPanel);


        panel.add(mainPanel, BorderLayout.CENTER);


        return panel;
    }


    private JPanel createSectionPanel(String title, Color color) {
        JPanel panel = new JPanel();
        panel.setBorder(BorderFactory.createTitledBorder(
                BorderFactory.createLineBorder(color, 2),
                title,
                TitledBorder.LEFT,
                TitledBorder.TOP,
                new Font("微软雅黑", Font.BOLD, 16),
                color
        ));
        panel.setBackground(new Color(5, 5, 5));
        return panel;
    }


    private JLabel createFormLabel(String text) {
        JLabel label = new JLabel(text);
        label.setFont(new Font("微软雅黑", Font.BOLD, 14));
        label.setHorizontalAlignment(SwingConstants.RIGHT);
        return label;
    }


    private JTextField createFormTextField() {
        JTextField textField = new JTextField();
        textField.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        return textField;
    }


    // 搜索面板
    private JPanel createSearchPanel() {
        JPanel panel = new JPanel(new BorderLayout(10, 10));
        panel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
        panel.setBackground(BACKGROUND_COLOR);


        // 搜索选项
        JPanel searchPanel = createSectionPanel("图书搜索", SECONDARY_COLOR);
        searchPanel.setLayout(new GridLayout(2, 1, 10, 15));
        searchPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));


        JPanel searchOptions = new JPanel(new FlowLayout(FlowLayout.CENTER, 15, 10));
        searchOptions.setOpaque(false);


        JLabel searchLabel = new JLabel("搜索条件:");
        searchLabel.setFont(new Font("微软雅黑", Font.BOLD, 14));


        JTextField searchField = new JTextField(25);
        searchField.setFont(new Font("微软雅黑", Font.PLAIN, 14));


        JComboBox<String> searchType = new JComboBox<>(new String[]{"书名", "作者", "分类"});
        searchType.setFont(new Font("微软雅黑", Font.PLAIN, 14));


        JButton searchButton = createStyledButton("搜索", SECONDARY_COLOR);


        searchOptions.add(searchLabel);
        searchOptions.add(searchField);
        searchOptions.add(searchType);
        searchOptions.add(searchButton);


        searchPanel.add(searchOptions);


        // 结果面板
        JPanel resultPanel = new JPanel(new BorderLayout());
        resultPanel.setOpaque(false);


        JLabel resultLabel = new JLabel("搜索结果:");
        resultLabel.setFont(new Font("微软雅黑", Font.BOLD, 14));
        resultLabel.setBorder(BorderFactory.createEmptyBorder(0, 0, 10, 0));
        resultPanel.add(resultLabel, BorderLayout.NORTH);


        // 结果表格
        String[] columnNames = {"ISBN", "书名", "作者", "分类", "状态", "借阅者"};
        DefaultTableModel model = new DefaultTableModel(columnNames, 0);
        JTable resultTable = new JTable(model);
        customizeTable(resultTable);


        JScrollPane scrollPane = new JScrollPane(resultTable);
        scrollPane.setBorder(BorderFactory.createEmptyBorder());
        resultPanel.add(scrollPane, BorderLayout.CENTER);


        searchPanel.add(resultPanel);


        // 搜索按钮事件
        searchButton.addActionListener(e -> {
            String keyword = searchField.getText().trim();
            String type = (String) searchType.getSelectedItem();


            if (keyword.isEmpty()) {
                showMessage("请输入搜索关键词！", "警告", JOptionPane.WARNING_MESSAGE);
                return;
            }


            List<Book> results = new ArrayList<>();
            switch (type) {
                case "书名":
                    results = library.searchByTitle(keyword);
                    break;
                case "作者":
                    results = library.searchByAuthor(keyword);
                    break;
                case "分类":
                    results = library.searchByCategory(keyword);
                    break;
            }


            model.setRowCount(0);
            for (Book book : results) {
                String borrowerName = "";
                if (!book.isAvailable()) {
                    borrowerName = library.getBorrowerName(book.getIsbn());
                }


                Object[] rowData = {
                        book.getIsbn(),
                        book.getTitle(),
                        book.getAuthor(),
                        book.getCategory(),
                        book.isAvailable() ? "可借" : "已借",
                        borrowerName
                };
                model.addRow(rowData);
            }


            if (results.isEmpty()) {
                showMessage("未找到匹配的图书！", "提示", JOptionPane.INFORMATION_MESSAGE);
            }
        });


        panel.add(searchPanel, BorderLayout.CENTER);


        return panel;
    }


    // 统计面板
    private JPanel createStatisticsPanel() {
        JPanel panel = new JPanel(new BorderLayout(10, 10));
        panel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
        panel.setBackground(BACKGROUND_COLOR);


        JPanel statsPanel = createSectionPanel("借阅统计", new Color(155, 89, 182));
        statsPanel.setLayout(new GridLayout(3, 1, 20, 20));
        statsPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));


        // 统计卡片1：图书统计
        JPanel bookStats = createStatCard("📚 图书统计",
                "图书总数: " + library.getAllBooks().size(),
                "可借图书: " + countAvailableBooks(),
                "已借图书: " + (library.getAllBooks().size() - countAvailableBooks()));


        // 统计卡片2：用户统计
        JPanel userStats = createStatCard("👥 用户统计",
                "用户总数: " + library.getAllUsers().size(),
                "活跃用户: " + countActiveUsers(),
                "最多借阅: " + getTopBorrower());


        // 统计卡片3：分类统计
        JPanel categoryStats = createStatCard("📊 分类统计",
                "最受欢迎: " + getPopularCategory(),
                "最少借阅: " + getLeastPopularCategory(),
                "分类总数: " + library.getCategories().size());


        statsPanel.add(bookStats);
        statsPanel.add(userStats);
        statsPanel.add(categoryStats);


        panel.add(statsPanel, BorderLayout.CENTER);


        return panel;
    }


    private JPanel createStatCard(String title, String stat1, String stat2, String stat3) {
        JPanel card = new JPanel(new GridLayout(4, 1, 5, 5));
        card.setBackground(Color.WHITE);
        card.setBorder(BorderFactory.createCompoundBorder(
        ));


        JLabel titleLabel = new JLabel(title);
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 16));
        titleLabel.setForeground(PRIMARY_COLOR);


        JLabel stat1Label = new JLabel(stat1);
        stat1Label.setFont(new Font("微软雅黑", Font.PLAIN, 14));


        JLabel stat2Label = new JLabel(stat2);
        stat2Label.setFont(new Font("微软雅黑", Font.PLAIN, 14));


        JLabel stat3Label = new JLabel(stat3);
        stat3Label.setFont(new Font("微软雅黑", Font.PLAIN, 14));


        card.add(titleLabel);
        card.add(stat1Label);
        card.add(stat2Label);
        card.add(stat3Label);


        return card;
    }


    private int countAvailableBooks() {
        int count = 0;
        for (Book book : library.getAllBooks()) {
            if (book.isAvailable()) count++;
        }
        return count;
    }


    private int countActiveUsers() {
        int count = 0;
        for (User user : library.getAllUsers()) {
            if (!user.getBorrowedBooks().isEmpty()) count++;
        }
        return count;
    }


    private String getTopBorrower() {
        String topBorrower = "无";
        int maxBooks = 0;


        for (User user : library.getAllUsers()) {
            int borrowedCount = user.getBorrowedBooks().size();
            if (borrowedCount > maxBooks) {
                maxBooks = borrowedCount;
                topBorrower = user.getName() + " (" + borrowedCount + "本)";
            }
        }


        return topBorrower;
    }


    private String getPopularCategory() {
        Map<String, Integer> categoryCount = new HashMap<>();


        for (Book book : library.getAllBooks()) {
            if (!book.isAvailable()) {
                String category = book.getCategory();
                categoryCount.put(category, categoryCount.getOrDefault(category, 0) + 1);
            }
        }


        return getTopCategory(categoryCount);
    }


    private String getLeastPopularCategory() {
        Map<String, Integer> categoryCount = new HashMap<>();


        // 初始化所有分类
        for (String category : library.getCategories()) {
            categoryCount.put(category, 0);
        }


        // 统计借阅数量
        for (Book book : library.getAllBooks()) {
            if (!book.isAvailable()) {
                String category = book.getCategory();
                categoryCount.put(category, categoryCount.getOrDefault(category, 0) + 1);
            }
        }


        // 找到借阅最少的分类
        String leastCategory = "无";
        int minCount = Integer.MAX_VALUE;


        for (Map.Entry<String, Integer> entry : categoryCount.entrySet()) {
            if (entry.getValue() < minCount) {
                minCount = entry.getValue();
                leastCategory = entry.getKey();
            }
        }


        return leastCategory + " (" + minCount + "本)";
    }


    private String getTopCategory(Map<String, Integer> categoryCount) {
        String topCategory = "无";
        int maxCount = 0;


        for (Map.Entry<String, Integer> entry : categoryCount.entrySet()) {
            if (entry.getValue() > maxCount) {
                maxCount = entry.getValue();
                topCategory = entry.getKey();
            }
        }


        return topCategory + " (" + maxCount + "本)";
    }


    private void showMessage(String message, String title, int messageType) {
        JOptionPane.showMessageDialog(this, message, title, messageType);
    }
}


